package fr.mairie.parc.page.commande;

import javax.annotation.Resource;

import org.apache.click.control.Form;
import org.apache.click.control.ImageSubmit;
import org.apache.click.util.Bindable;
import org.springframework.context.ApplicationContext;

import fr.mairie.parc.context.AppContext;
import fr.mairie.parc.control.commande.CommandeFields;
import fr.mairie.parc.control.commande.CommandeValidationFields;
import fr.mairie.parc.domain.Commande;
import fr.mairie.parc.page.BorderPage;
import fr.mairie.parc.service.CommandeManager;

public class EditCommandePage extends BorderPage {

	private static final long serialVersionUID = 1L;

	@Resource protected CommandeManager commandeManager;
	@Bindable protected Form form = new Form();
	@Bindable protected Integer idCommande;
	protected transient Commande commande;



	protected CommandeFields fields = new CommandeFields(true);
	protected CommandeValidationFields commandeValidation = new CommandeValidationFields();

	public EditCommandePage() {
		fields.addAll(form);
		commandeValidation.addTo(form);
		form.add(new ImageSubmit("OK", "/assets/images/32x32/accept.png", this,"onSubmit"));
		form.add(new ImageSubmit("Cancel", "/assets/images/32x32/cancel.png",this, "onCancelClicked"));
	}

	@Override
	public void onInit() {
		super.onInit();
		ApplicationContext ctx = AppContext.getApplicationContext();
    	commandeManager = (CommandeManager) ctx.getBean("commandeManager");
	}

	@Override
	public void onRender() {
		if (idCommande < 0) {
			msg = "Error, invalid id:" + idCommande + " for Commande";
			setRedirect("error.htm");
			return;
		}
		if (commande == null) {
			commande =  commandeManager.getCommandeById(idCommande);
		}
		if (commande == null) {
			msg = "Error, Commande not found for id:" + idCommande;
			setRedirect("error.htm");
			return;
		}

		fields.setFieldsValues(commande);
		commandeValidation.setFieldValues(commande);
		super.onRender();
	}

	public boolean onCancelClicked() {
        setRedirect(CommandePage.class);
        return false;
    }

	public boolean onSubmit() {
		if (form.isValid()) {
			// step 1: unmarshall params from web form, fill DTO to call server
			Commande in = new Commande();
			in.setIdCommande(fields.getIdCommande());
			commandeValidation.getFieldValues(in);

			// step2: *** The biggy : call server with DTO params, do XA business code ***
			commandeManager.updateCommande(in);



			// step 3: render result from DTO to web, redirect page

		} else {
			msg = "Validation Error, please fill fields";
		}
		return true;
	}

}
